package com.keter.common.exp;

import com.keter.common.base.BaseController;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPOutputStream;

@RestController
public class GzipExpController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(GzipExpController.class);
    /**
     * Gzip压缩测试：使用ISO-8859-1字符集编解码测试成功
     *
     * @return
     */
    @GetMapping(value = "/exp/gzip", produces = "text/compressed;charset=ISO-8859-1")
    public String gzip() throws UnsupportedEncodingException {
       String content = "哈哈hahahahaha哈哈";
        logger.info("size:{}", content.getBytes().length);
        return getISOString(content);
    }

    /**
     * 浏览器可以正确解压
     * 但RestTemplate使用GZIPInputStream解压时会报错：java.util.zip.ZipException: Not in GZIP format
     * Explain：
     * String outStr = out.toString("UTF-8");
     * This "out" is ziped byte stream,encode it to String then decode it from String will be lose some bytes.This maybe a bug of java.
     * https://stackoverflow.com/questions/26528256/exception-in-thread-main-java-util-zip-zipexception-not-in-gzip-format-when
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value = "/exp/gzipu8",produces = "text/compressed;charset=UTF-8")
    public String gzipu8(HttpServletRequest request) throws UnsupportedEncodingException {
        logger.info("headers:{}", request.getHeader("Accept-Encoding"));
        return  new String("哈哈hahahahahhaha哈哈".getBytes(), "UTF-8");
    }

    @GetMapping(value = "/exp/gzipu8enforce",produces = "text/compressed;charset=UTF-8")
    public String gzipu8enforce(HttpServletRequest request) throws IOException {
        logger.info("headers:{}", request.getHeader("Accept-Encoding"));
        return  compress(new String("哈哈hahahahahhaha哈哈".getBytes(), "UTF-8"));
    }

    private String getISOString(String s) throws UnsupportedEncodingException {
        return new String(s.getBytes(), "ISO-8859-1");
    }

    /**
     * 自定义内容类型（避免被自动压缩）和自性实现base64编码的压缩字节数组
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/exp/gzipu8base64", produces = "text/mycontent;charset=UTF-8")
    public String gzipu8base64() throws IOException {
		String content = "哈哈haha哈哈haha内容得一点少了压缩后反而更多哈哈haha哈哈haha内容得一点少了压缩后反而更多哈哈haha哈哈haha内容得一点少了压缩后反而更多哈哈haha哈哈";
        return compressBase64(content);
    }

    @GetMapping(value = "/ungzip")
    public String ungzip() {
        //长度不足:不进行压缩
        return "hahahahahahaha";
    }

    private String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        String outStr = new String(out.toByteArray());
        return outStr;
    }

    private String compressBase64(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        System.out.println("String length : " + str.length());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes("ISO-8859-1"));
        gzip.close();
        String outStr = new String(Base64.encodeBase64(out.toByteArray()));
        System.out.println("Output String lenght : " + outStr.length());
        System.out.println("Output : " + outStr);
        return outStr;
    }
}
